<template>
  <basic-container>
    <div class="card-container">
      <avue-form :option="option" v-model="form" @submit="handleSearch"></avue-form>
    </div>
    <div class="card-container">
      <chart-view class="chart-content" :chart-option="chartOption" :auto-resize="true" width="100%" @click="handleClick" />
    </div>
    <div class="card-container">
      <avue-crud
        :option="detailOption"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :search.sync="query"
        ref="crud"
        @size-change="sizeChange"
        @current-change="currentChange"
      >
        <template slot="menuLeft">
          <!--            v-if="permission.ontimeDeliveryRate_import"-->
          <el-button type="success" size="small" icon="el-icon-download" @click="handleImport()">导 出</el-button>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <!--            v-if="permission.ontimeDeliveryRate_import"-->
          <el-button type="text" size="small" @click="viewDetail(row)">工单详情</el-button>
        </template>
      </avue-crud>
    </div>
    <el-dialog title="工单详情" :visible.sync="detailDialog" width="80%" append-to-body :close-on-press-escape="false" :before-close="handleCancel" top="3vh">
      <div class="sail-header-dialog-content">
        <avue-form :option="detailFormOption" v-model="detailForm">
          <template slot="workOrderTable">
            <avue-crud :option="workOrderTableOption" :data="form.workOrderVOList || []"></avue-crud>
          </template>
          <template slot="processTable">占坑</template>
          <template slot="materialTable">占坑</template>
          <template slot="productTable">占坑</template>
          <template slot="warehouseTable">
            <avue-crud :option="warehouseTableOption" :data="form.finishedInboundRecordVOList || []"></avue-crud>
          </template>
        </avue-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-product/ems-equipment/page" :option="option" :page="page" :query="exportParams" file-name="准时交付率"> </export-comp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import moment from 'moment';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportComp from '@/components/export-comp/index.vue';
import ChartView from '@/components/chart/index.vue';
import { mapGetters } from 'vuex';
import { detailFormOption, workOrderTableOption, processTableOption, warehouseTableOption, productTableOption } from '@/views/report/ontimeDeliveryRate';
import { getList, getTableList, getDetail } from '@/api/product/ontimeDeliveryRate';

export default {
  name: 'ontimeDeliveryRate',
  components: {
    exportComp,
    ChartView,
    CommonModalTemplate
  },
  data() {
    return {
      exportParams: {},
      workOrderTableOption,
      processTableOption,
      warehouseTableOption,
      productTableOption,
      timer: new Date().getTime(),
      tableOption: {},
      form: {},
      detailForm: {},
      detailFormOption,
      detailDialog: false,
      query: {},
      option: {
        submitBtn: true,
        emptyBtn: true,
        submitText: '搜索',
        submitIcon: 'el-icon-search',
        menuPosition: 'right',
        span: 6,
        labelWidth: 120,
        column: [
          {
            label: '图表展示维度',
            prop: 'dimension',
            type: 'radio',
            button: true,
            span: 4,
            value: 'DAY',
            dicData: [
              {
                label: '日',
                value: 'DAY'
              },
              {
                label: '周',
                value: 'WEEK'
              },
              {
                label: '月',
                value: 'MONTH'
              }
            ]
          },
          {
            label: '客户编码',
            span: 6,
            prop: 'customerCode',
            type: 'search',
            appendClick: () => {
              this.openPartnerModal();
            }
          },
          {
            label: '要求交付日期',
            span: 6,
            prop: 'date',
            type: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            control: (val, form) => {
              console.log(form.dimension);
              if (form.dimension === 'DAY') {
                return {
                  date: { display: true }
                };
              } else {
                return {
                  date: { display: false }
                };
              }
            },
            rules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              },
              {
                trigger: 'change',
                validator: (rule, value, callback) => {
                  const endTime = value[1];
                  const startTime = value[0];
                  if (moment(endTime).diff(moment(startTime), 'day') >= 30) {
                    callback(new Error('查询时间最多选择30天'));
                  }
                  callback();
                }
              }
            ]
          },
          {
            label: '要求交付日期起始周',
            span: 6,
            prop: 'weekStart',
            type: 'week',
            labelWidth: 160,
            format: 'yyyy 第 WW 周',
            valueFormat: 'yyyy-MM-dd',
            rules: [
              {
                required: true,
                message: '请选择起始周范围',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (form.dimension === 'WEEK') {
                return {
                  weekStart: { display: true }
                };
              } else {
                return {
                  weekStart: { display: false }
                };
              }
            }
          },
          {
            label: '要求交付日期结束周',
            labelWidth: 160,
            span: 6,
            prop: 'weekEnd',
            type: 'week',
            format: 'yyyy 第 WW 周',
            valueFormat: 'yyyy-MM-dd',
            rules: [
              {
                required: true,
                message: '请选择结束周范围',
                trigger: 'blur'
              },
              {
                trigger: 'change',
                validator: this.validateWeek
              }
            ],
            control: (val, form) => {
              if (form.dimension === 'WEEK') {
                return {
                  weekEnd: { display: true }
                };
              } else {
                return {
                  weekEnd: { display: false }
                };
              }
            }
          },
          {
            label: '要求交付日期',
            span: 6,
            prop: 'month',
            type: 'monthrange',
            format: 'yyyy-MM',
            valueFormat: 'yyyy-MM',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            rules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              },
              {
                trigger: 'change',
                validator: (rule, value, callback) => {
                  const endTime = value[1];
                  const startTime = value[0];

                  if (moment(endTime).diff(moment(startTime), 'month') > 12) {
                    callback(new Error('查询时间最多选择12个月'));
                  }
                  callback();
                }
              }
            ],
            control: (val, form) => {
              if (form.dimension === 'MONTH') {
                return {
                  month: { display: true }
                };
              } else {
                return {
                  month: { display: false }
                };
              }
            }
          }
        ]
      },
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailOption: {
        height: 'calc(100vh - 520px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        // searchMenuSpan: 6,
        searchLabelWidth: 140,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        labelWidth: 190,
        selection: true,
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        menu: true,
        columnBtn: false,
        refreshBtn: false,
        column: [
          { label: '要求交付日期', prop: 'planDeliveryDate' },
          { label: '客户编码', prop: 'customerName' },
          { label: '客户名称', prop: 'customerCode' },
          { label: '发货单号', prop: 'outboundOrderNo' },
          { label: '行号', prop: 'outboundOrderLot' },
          { label: '产品编码', prop: 'productPartName' },
          { label: '产品型号', prop: 'productPartModel' },
          { label: '需求数量', prop: 'planOutboundQuantity' },
          { label: '发货数量', prop: 'actualOutboundQuantity' },
          { label: '实际发货日期', prop: 'actualDeliveryTime' },
          { label: '准时发货', prop: 'isOnTimeDelivery' },
          { label: '下单日期', prop: 'outboundOrderCreateTime' }
        ]
      },
      selectName: '',
      chartOption: {
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            rotate: 80
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = params[0].axisValueLabel + '<br/>';
            params.forEach(function (item) {
              result += item.marker + item.seriesName + ': ' + item.data + '%<br/>';
            });
            return result;
          },
          textStyle: {
            rich: {
              a: {
                color: '#fff',
                backgroundColor: '#333',
                padding: [5, 10],
                borderRadius: 4
              }
            }
          }
        },
        legend: {
          data: ['实际交付率', '目标']
        },
        yAxis: {
          type: 'value',
          name: '实际交付率',
          min: 0,
          max: 120,
          axisLabel: {
            formatter: '{value} %'
          },
          nameLocation: 'middle',
          nameTextStyle: {
            fontSize: 14,
            align: 'center',
            verticalAlign: 'middle',
            lineHeight: 20,
            formatter: function (value) {
              return value.split('').join('\n'); // 将文字从上到下排列
            }
          },
          nameGap: 80 // 名称与轴线的间距
        },
        series: [
          {
            name: '实际交付率',
            data: [],
            type: 'bar',
            barWidth: '20',
            itemStyle: {
              color: '#abd78f' // 设置柱子的颜色
            }
          },
          {
            name: '目标',
            type: 'line',
            data: [], // 假设目标线为100%
            lineStyle: {
              color: '#89a6d8', // 设置目标线的颜色
              width: 2
            }
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  methods: {
    newKey() {
      this.timer = new Date().getTime();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getTableData();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getTableData();
    },
    async handleSearch(form, done) {
      const params = this.getParams();
      //  表单以分页的形式 返回。写死参数
      try {
        const res = await getList(1, 35, params);
        const data = res.data.data ? res.data.data.records : [];
        this.setChartData(data);
      } catch (e) {
        console.log(e);
      }
      done();
    },
    async viewDetail(row) {
      try {
        const res = await getDetail({ id: row.id });
        const data = res.data.data;
        this.detailForm = data;
        this.detailDialog = true;
      } catch (e) {
        console.log(e);
      }
    },
    handleImport() {
      if (!this.selectName) {
        this.$message.warning('请通过选择对应的图表数据进行导出');
        return;
      }
      this.exportParams = {
        dimensionTime: this.selectName,
        ...this.getChartParams()
      };
      this.$refs.exportComp.visible = true;
    },
    getParams() {
      const form = this.form;
      let dimension, customerCode, queryStartTime, queryEndTime;
      if (form.dimension === 'DAY') {
        dimension = '日';
        queryStartTime = form.date[0];
        queryEndTime = form.date[1];
      } else if (form.dimension === 'WEEK') {
        queryStartTime = this.formatDateToYearWeek(form.weekStart);
        queryEndTime = this.formatDateToYearWeek(form.weekEnd);
        dimension = '周';
      } else {
        queryStartTime = this.formatDateToYearMonth(form.month[0]);
        queryEndTime = this.formatDateToYearMonth(form.month[1]);
        dimension = '月';
      }
      if (form.customerCode) {
        customerCode = form.customerCode;
      }
      return {
        dimension,
        customerCode,
        queryStartTime,
        queryEndTime
      };
    },
    getChartParams() {
      const form = this.form;
      const name = this.selectName;
      let dimension;
      if (form.dimension === 'DAY') {
        dimension = '日';
      } else if (form.dimension === 'WEEK') {
        dimension = '周';
      } else {
        dimension = '月';
      }

      return {
        dimensionTime: name.replace('年', '-').replace('月', '').replace('周', ''),
        dimension,
        customerCode: form.code
      };
    },
    formatDateToYearWeek(dateString) {
      // 使用 moment 库解析日期字符串
      let date = moment(dateString);
      // 获取年份
      let year = date.format('YYYY');
      // 获取周数，ISO 标准下，星期一作为一周的第一天
      let week = date.isoWeek();
      // 格式化周数，确保周数是两位数
      let formattedWeek = week < 10 ? '0' + week : week;
      // 返回格式化后的字符串
      return year + '-' + formattedWeek;
    },
    formatDateToYearMonth(dateString) {
      // 使用 moment 库解析日期字符串
      let date = moment(dateString, 'YYYY-MM-D');
      // 获取年份
      let year = date.format('YYYY');
      // 获取月份，格式化为两位数
      let month = date.format('MM');
      // 返回格式化后的字符串
      return year + '-' + month;
    },

    setChartData(data = []) {
      const xAxisData = [];
      const yAxisData = [];
      data.forEach((item) => {
        let dimensionTime = item.dimensionTime;
        if (this.form.dimension === 'DAY') {
          xAxisData.push(item.dimensionTime);
        } else if (this.form.dimension === 'WEEK') {
          const dateArr = dimensionTime.split('-');
          const year = dateArr[0];
          const week = dateArr[1];
          xAxisData.push(`${year}年${week}周`);
        } else {
          const dateArr = dimensionTime.split('-');
          const year = dateArr[0];
          const moth = dateArr[1];
          xAxisData.push(`${year}年${moth}月`);
        }
        const deliveryRate = item.deliveryRate ? Number(item.deliveryRate) * 100 : 0;
        yAxisData.push(deliveryRate);
      });
      const len = data.length;
      this.$set(this.chartOption.xAxis, 'data', xAxisData);
      this.$set(this.chartOption.series[0], 'data', yAxisData);
      this.$set(this.chartOption.series[1], 'data', Array(len).fill(100));
    },
    async handleClick(value) {
      const name = value.name;
      if (name) {
        this.selectName = name;
        await this.getTableData();
      }
    },
    handleCancel() {
      this.detailDialog = false;
    },
    async getTableData() {
      try {
        const params = {
          dimensionTime: this.selectName,
          ...this.getChartParams()
        };
        this.loading = true;
        const res = await getTableList(this.page.currentPage, this.page.pageSize, params);
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    },
    getSelectedRows(rowData) {
      this.form.customerCode = rowData.code || '';
    },
    validateWeek(rule, value, callback) {
      const startTime = moment(this.form.weekStart, 'yyyy-MM-DD');
      const endTime = moment(this.form.weekEnd, 'yyyy-MM-DD');
      const monthDiff = endTime.diff(startTime, 'days');
      if (monthDiff >= 84) {
        callback(new Error('时间范围不能超过8周'));
      } else if (monthDiff < 0) {
        callback(new Error('结束周不能早于开始周'));
      } else {
        callback();
      }
    },
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择客户信息（双击进行选择）',
        url: '/api/mes-admin/customer/page',
        isPage: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'partnerInfo',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss">
.card-container {
  border: 1px solid #ebeef5;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  padding: 16px;
  margin: 8px;
  border-radius: 8px;
  background-color: #fff;
}
</style>
